package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.ClubActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.ClubItemDto;
import com.ca.ridersclubapplication.util.ImageCacheUtils;
import com.ca.ridersclubapplication.util.NumberUtils;

import java.util.ArrayList;
import java.util.List;

public class ClubAdapter extends RecyclerView.Adapter<ClubAdapter.ClubHolder> {


    private final Activity activity;
    private List<ClubItemDto> list;

    public ClubAdapter(Activity activity, List<ClubItemDto> list) {
        this.activity = activity;
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public ClubHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.club_item_layout, parent, false);
        return new ClubHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ClubHolder holder, int position) {

        ClubItemDto dto = list.get(position);
        holder.nameView.setText(dto.getName());;
        String text = NumberUtils.numberToString(dto.getPaperCount()) + "条动态";
        holder.paperCountView.setText(text);
        ImageCacheUtils.loadRoundImage(activity, FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId(), holder.imageView);

        holder.parent.setOnClickListener(v -> {
            Intent intent = new Intent(activity, ClubActivity.class);
            intent.putExtra("clubId", dto.getId());
            activity.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<ClubItemDto> list) {
        this.list = list == null ? new ArrayList<>() : list;
        notifyDataSetChanged();
    }

    public static class ClubHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView nameView;
        public TextView paperCountView;
        public ConstraintLayout parent;


        public ClubHolder(@NonNull View itemView) {
            super(itemView);

            parent = itemView.findViewById(R.id.cl_parent);
            imageView = itemView.findViewById(R.id.iv);
            nameView = itemView.findViewById(R.id.tv_name);
            paperCountView = itemView.findViewById(R.id.tv_paperCount);
        }
    }
}
